﻿namespace _01单例模式.反射破坏单例模式
{
    /// <summary>
    /// 通过反射破坏创建对象
    /// </summary>
    public class SingleLayMan1
    { 
        //私有化构造函数
        private SingleLayMan1()
        {
        }
        //2、声明静态字段  存储我们唯一的对象实例
        private static SingleLayMan1? _singleLayMan;
        private static object _oj = new object();

        /// <summary>
        /// //解决多线程安全问题，双重锁定，减少系统消耗，节约资源
        /// </summary>
        public static SingleLayMan1 GetSingleLayMan()
        {
            if (_singleLayMan == null)
            {
                lock (_oj)
                {
                    if (_singleLayMan == null)
                    {
                        _singleLayMan = new SingleLayMan1();
                        Console.WriteLine("我被创建了一次！");
                    }
                }
            }           
            return _singleLayMan;
        }        
    }

    public class SingleLayManTest1
    {
        public static void FactTestReflection()
        {
            var singleLayMan1= SingleLayMan1.GetSingleLayMan();

            var type = Type.GetType("_01单例模式.反射破坏单例模式.SingleLayMan1");
            //获取私有的构造函数
            var ctors = type?.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            //执行构造函数
            SingleLayMan1 singleLayMan = (SingleLayMan1)ctors[0].Invoke(null);
            Console.WriteLine(singleLayMan1.GetHashCode());
            Console.WriteLine(singleLayMan.GetHashCode());
        }
    }
}
